package au.edu.unsw.editingtool.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import au.edu.unsw.editingtool.db.DBClaims;
import au.edu.unsw.editingtool.db.DBLogin;
import au.edu.unsw.editingtool.global.EditingToolGlobalConstant;

/**
 * Servlet implementation class ClaimHandler
 */
public class ClaimHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ClaimHandler() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doService(request, response);
	}
	
	protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//serve both addclaims and changeclaim status.
		String cmd = request.getParameter(EditingToolGlobalConstant.commandClaim);
		if (cmd.equals(EditingToolGlobalConstant.claimCommandApprove)) {
			
		} else if (cmd.equals(EditingToolGlobalConstant.claimCommandAdd)) {
			try {
				populateIntoClaims(request);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (cmd.equals(EditingToolGlobalConstant.claimCommandDeny)) {
			
		}
	}
	
	private void populateIntoClaims(HttpServletRequest req) throws SQLException, ClassNotFoundException {
		Hashtable<String, String> trunk = new Hashtable<String, String>();
		String author = req.getParameter(EditingToolGlobalConstant.requestUsername);
		
		DBLogin user = new DBLogin();
		trunk.put("Username", author);
		
		String result[][] = user.getInfoViaPrimaryKeys(trunk, new String[]{"Affiliation"});
		trunk.clear();
		user.clean();
		
		DBClaims claims = new DBClaims();
		trunk.put("Author", author);
		trunk.put("Affiliation", result[0][0]);
		trunk.put("Publication", req.getParameter(EditingToolGlobalConstant.requestPid));
		claims.addClaim(trunk);
	}

}
